package com.crm.system.service.impl.contractManager;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.ContractStatusEnum;
import com.crm.common.model.Enum.ContractTypeEnum;
import com.crm.common.model.Enum.PaymentMethodEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.ESUtil;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.contractManager.CustomerContractDeveloper;
import com.crm.model.entity.couponManager.Coupon;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.opportunityManager.Opportunity;
import com.crm.model.entity.orderManager.CustomerOrderActivityRelation;
import com.crm.model.entity.orderManager.CustomerOrderGiftRelation;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.orderManager.CustomerProductOrderDetail;
import com.crm.model.entity.productManager.CustomerMemberProduct;
import com.crm.model.entity.productManager.CustomerProduct;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.contractManager.*;
import com.crm.model.vo.cluePoolManager.CluePoolVO;
import com.crm.model.vo.contractReviewManager.UpdateContractVO;
import com.crm.model.vo.customerContractManager.ContractLastThreeMonthVO;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.contractManager.CustomerContractDeveloperDbService;
import com.crm.service.csd.customerManager.ContractContactDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.opportunityManager.OpportunityDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.orderManager.CustomerProductOrderDetailDbService;
import com.crm.service.productManager.CustomerMemberProductDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.system.service.contractManager.UpgradeContractService;
import com.crm.system.service.customerManager.CustomerService;
import com.crm.system.service.orderManager.CustomerProductOrderService;
import com.crm.system.service.user.UserAccountService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author luojie
 * @date 2021/9/22 15:25
 */
@Service
public class UpgradeContractServiceImpl implements UpgradeContractService {

    @Value("${esurl}")
    public String ESurl;
    @Autowired
    private CustomerContractDbService customerContractDbService;
    @Autowired
    private CustomerProductOrderDetailDbService customerProductOrderDetailDbService;
    @Autowired
    private CustomerMemberProductDbService customerMemberProductDbService;
    @Autowired
    private CustomerDbService customerDbService;
    @Autowired
    private CustomerProductOrderDbService customerProductOrderDbService;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private CustomerContractDeveloperDbService customerContractDeveloperDbService;
    @Autowired
    private FinishOrderDBservice finishOrderDBservice;
    @Autowired
    private CustomerProductOrderService customerProductOrderService;
    @Autowired
    private OpportunityDbService opportunityDbService;


    @Override
    public DhPageInfo<FinishOrderProduct> selectOldContractProductByContractId(String contractId,Integer pageIndex,Integer pageSize) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        CustomerContract customerContract = customerContractDbService.selectContractById(contractId);
        String orderId = customerContract.getOrderId();
        if(!StringUtils.isBlank(orderId)){
            List<FinishOrderProduct> finishOrderProductList = finishOrderDBservice.selectNoExchangeFinishOrderProductListByOrderId("1","1",orderId);
            PageInfo<FinishOrderProduct> pageInfo = new PageInfo<FinishOrderProduct>(finishOrderProductList);
            //List<CustomerProductOrderDetail> customerProductOrderDetailList = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(orderId,"1");
            return new DhPageInfo<FinishOrderProduct>(pageInfo, finishOrderProductList);
        }else {
            return null;
        }
    }

    @Override
    public List<CustomerMemberProduct> selectUpgradeMemberProductList(String contractId, String productName,String whetherRenew) {
        CustomerContract customerContract = customerContractDbService.selectContractById(contractId);
        String orderId = customerContract.getOrderId();
        List<CustomerProductOrderDetail> customerProductOrderDetailList = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(orderId,"1");
        List<CustomerMemberProduct> jsonObjectListResult = new ArrayList<CustomerMemberProduct>();
        List<CustomerMemberProduct> customerMemberProductList = customerMemberProductDbService.selectContractMemberProductList(productName,whetherRenew,"upgrade");
        customerMemberProductList.stream().forEach(customerMemberProduct -> {
            //会员产品在不在当前产品中
            if (customerProductOrderDetailList.stream().filter(w->w.getOrderRelationId().equals(customerMemberProduct.getMemberProductId())).findAny().isPresent()){
                //说明有则退出
                return;
            }else {
                jsonObjectListResult.add(customerMemberProduct);
            }

        });
        return jsonObjectListResult;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean addUpgradeContract(UpdateContractAddQO updateContractAddQO) {
        //1、新增、编辑合同信息
        CustomerContract customerContract = addContract(updateContractAddQO);
        //合同id
        String contractId = customerContract.getContractId();
        if (!StringUtils.isBlank(contractId)) {

            //2、新增、编辑订单
            CustomerProductOrder customerProductOrder = addContractOrder(customerContract);
            String orderId = customerProductOrder.getProductOrderId();

            //3、新增、编辑合作开发人员同时计算合作开发业绩
            addContractDeveloper(updateContractAddQO,contractId,orderId);

            //5、新增、更新订单详情表
            if (!StringUtils.isBlank(orderId)) {
                addOrderDetail(updateContractAddQO, orderId);

            }
            //6、如果是新增合同,更新合同表中订单id
            CustomerContract customerContractUpdate = new CustomerContract();
            customerContractUpdate.setContractId(contractId);
            customerContractUpdate.setOrderId(orderId);
            customerContractDbService.updateCustomerContract(customerContractUpdate);

            //7、插入finish表
            insertFinishOrderProduct(customerContract,orderId,customerProductOrder.getOrderNumber());

            //8、修改原合同已兑换的产品finish表修改成已兑换
            String finishOrderProductId = updateContractAddQO.getFinishOrderProductId();
            finishOrderDBservice.updateFinishOrderProductExchangeStatus(finishOrderProductId,"1");

/*          //9、查询原合同所有产品是否已经兑换，如果全部已经兑换，合同作废，卡失效
            Boolean resultBoolean = false;
            List<FinishOrderProduct> finishOrderProductList = finishOrderDBservice.selectFinishOrderProductList("1","1",orderId);
            for (FinishOrderProduct finishOrderProduct : finishOrderProductList) {
                if("1".equals(finishOrderProduct.getExchangeStatus())){
                    resultBoolean = true;
                    break;
                }
            }

            if(resultBoolean){
                //作废合同
                //1:将合同状态置为已作废(chs_customer_contract),合同状态：contractStatus为4
                customerContractDbService.updateContractStatusById(contractId, ContractStatusEnum.ABOLISHED.getContractStatus());
                //2:将订单状态置为作废(chs_customer_product_order)
                customerProductOrderDbService.updateOrderStatusByContractId(contractId);
                //5:将finish表的产品删除标识设置为1
                finishOrderDBservice.delOrderProductByOrderId(customerContract.getOrderId());

                //6:作废会员卡
                invalidMembershipCard(customerContract.getOrderId());
            }*/

            //8、如果不是线下支付，进行扣款，等审核通过后再往回款表中插入数据
            String paymentMethod = updateContractAddQO.getPaymentMethod();
            if(!PaymentMethodEnum.OFFLINE_PAYMENT.getPaymentMethod().equals(paymentMethod)){
                deduction(updateContractAddQO,customerContract);
            }

        }

        return true;
    }

    //扣款操作
    public void deduction(UpdateContractAddQO updateContractAddQO,CustomerContract customerContract) {
        String paymentMethod = updateContractAddQO.getPaymentMethod();
        BigDecimal contractReceivables = updateContractAddQO.getReplenishmentAmount();
        Customer customerOld = customerDbService.selectCustomerById(customerContract.getCustomerId());
        if (StringUtils.isEmpty(paymentMethod)) {
            return;
        }
        //如果支付方式不是线下支付
        if (!PaymentMethodEnum.OFFLINE_PAYMENT.getPaymentMethod().equals(paymentMethod)) {
            Customer customerNew = new Customer();
            customerNew.setCustomerId(customerContract.getCustomerId());
            //插入回款表
            List<HashMap> returnList = new ArrayList<>();
            //更新客户信息
            //2:线下支付;3:余额支付;4:转入额支付;5:余额＋转入额支付;
            switch (paymentMethod) {
                case "3": {
                    customerNew.setCustomerWallet(customerOld.getCustomerWallet().subtract(contractReceivables));
                    customerDbService.updateCustomerById(customerNew);

/*                    //进行全额回款
                    returnMoney(customerContractAddQO,contractId,orderId);
                    //发送回款消息
                    insertMessage(contractNumber);*/
                    break;
                }
                case "4": {
                    customerNew.setCustomerShiftWallet(customerOld.getCustomerShiftWallet().subtract(contractReceivables));
                    customerDbService.updateCustomerById(customerNew);

/*                    //进行全额回款
                    returnMoney(customerContractAddQO,contractId,orderId);
                    //发送回款消息
                    insertMessage(contractNumber);*/
                    break;
                }
 /*                case "5": {
                    if (customerOld.getCustomerShiftWallet().compareTo(contractReceivables) == -1) {
                        customerNew.setCustomerShiftWallet(BigDecimal.valueOf(0));
                        customerNew.setCustomerWallet(contractReceivables.subtract(customerOld.getCustomerShiftWallet()));
                    } else {
                        customerNew.setCustomerShiftWallet(customerOld.getCustomerShiftWallet().subtract(contractReceivables));
                    }
                    customerDbService.updateCustomerById(customerNew);
                    //存入
                    //转入额
                   HashMap hashMap1 = new HashMap();
                    hashMap1.put("paymentMethod", 4);
                    hashMap1.put("amount", customerOld.getCustomerShiftWallet());
                    returnList.add(hashMap1);
                    //余额
                   HashMap hashMap2 = new HashMap();
                    hashMap2.put("paymentMethod", 2);
                    hashMap2.put("amount", contractReceivables.subtract(customerOld.getCustomerShiftWallet()));
                    returnList.add(hashMap2);
                    insertReturnMoney(returnList, contractId, orderId, customerContractAddQO.getCustomerId(), customerContractAddQO.getContractType());
                    //更新订单，更新合同
                    if ("0".equals(customerContractAddQO.getWhetherCheck())) {
                        updateOrderAndContract(contractId, orderId, contractReceivables);
                    }
                    break;
                }*/
                default:
                    break;
            }

        }
    }

    @Override
    public UpdateContractVO getUpgradeContractDetail(String contractId) {
        CustomerContract customerContract = customerContractDbService.selectContractById(contractId);
        String upgradeRelateContractId = customerContract.getUpgradeRelateContract();
        String upgradeRelateFinishProductId = customerContract.getUpgradeRelateFinishProductId();
        FinishOrderProduct finishOrderProduct = finishOrderDBservice.selectFinishOrderProductById(upgradeRelateFinishProductId);
        UpdateContractVO updateContractVO = new UpdateContractVO();
        //当前合同id
        updateContractVO.setCurrentContractId(upgradeRelateContractId);
        CustomerContract upgradeContract = customerContractDbService.selectContractById(upgradeRelateContractId);
        //当前合同编号
        updateContractVO.setCurrentContractNumber(upgradeContract.getContractNumber());
        //兑换前产品明细

        updateContractVO.setCurrentProductId(finishOrderProduct.getProductId());
        updateContractVO.setCurrentProductCode(finishOrderProduct.getProductCode());
        updateContractVO.setCurrentProductName(finishOrderProduct.getProductName());
        updateContractVO.setCurrentProductDealPrice(finishOrderProduct.getProductFinalPrice());
        updateContractVO.setCurrentOrderId(finishOrderProduct.getProductOrderId());
        updateContractVO.setCurrentFinishOrderProductNum(finishOrderProduct.getFinishOrderProductNum());
        updateContractVO.setCurrentCustomerId(customerContract.getCustomerId());

        String orderId = customerContract.getOrderId();
        List<FinishOrderProduct> finishOrderProductList = finishOrderDBservice.selectFinishOrderProductList("1", "1", orderId);
        //兑换后产品明细
        FinishOrderProduct finishOrderProduct1 = finishOrderProductList.get(0);
        updateContractVO.setUpdateProductId(finishOrderProduct1.getProductId());
        updateContractVO.setUpdateProductName(finishOrderProduct1.getProductName());
        updateContractVO.setUpdateProductCode(finishOrderProduct1.getProductCode());
        updateContractVO.setReplenishmentAmount(finishOrderProduct1.getProductFinalPrice());
        updateContractVO.setUpdateProductMemberPrice(finishOrderProduct1.getProductMemberPrice());
        return updateContractVO;
    }

    @Override
    public List<ContractLastThreeMonthVO> getLastThreeMonthsContractList() {
        UserAccount userAccount = (UserAccount)SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        List<ContractLastThreeMonthVO> customerContractList = customerContractDbService.selectLastThreeMonthsContractList(userAccount.getAccountId());
        return customerContractList;
    }

    public CustomerContract addContract(UpdateContractAddQO updateContractAddQO){
        UserAccount userAccount = (UserAccount)SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        String contractId = updateContractAddQO.getContractId();
        CustomerContract oldContract = customerContractDbService.selectContractById(contractId);
        CustomerContract customerContract = new CustomerContract();
        customerContract.setCustomerId(oldContract.getCustomerId());
        customerContract.setCustomerName(oldContract.getCustomerName());
        customerContract.setCustomerType(oldContract.getCustomerType());

        customerContract.setPayBackDate(oldContract.getPayBackDate());
        customerContract.setPaymentAccount(oldContract.getPaymentAccount());
        customerContract.setContractActualTotalAmount(updateContractAddQO.getReplenishmentAmount());
        //1-补款升级合同；2-兑换合同
        customerContract.setContractOtherType("1");
        customerContract.setUpgradeRelateContract(contractId);
        //不是老合同
        customerContract.setOldContract("0");
        //是否需要核验
        customerContract.setWhetherCheck("1");
        //合同开发人员
        List<ContractCoDeveloperQO> coDeveloperList = updateContractAddQO.getCoDeveloperList();
        if (coDeveloperList != null && coDeveloperList.size()>0) {
            customerContract.setWhetherCooperateDevelopment("1");
        } else {
            customerContract.setWhetherCooperateDevelopment("0");
        }

        //是否是会员单次合同，7是会员单次合同
        if("7".equals(oldContract.getContractType())){
            customerContract.setContractType(updateContractAddQO.getContractType());
            customerContract.setCustomerEmail(updateContractAddQO.getCustomerEmail());
            customerContract.setContractStartDate(updateContractAddQO.getContractStartDate());
            customerContract.setContractEndDate(updateContractAddQO.getContractEndDate());
        }else {
            customerContract.setContractType(oldContract.getContractType());
            customerContract.setCustomerEmail(oldContract.getCustomerEmail());
            customerContract.setContractStartDate(oldContract.getContractStartDate());
            customerContract.setContractEndDate(oldContract.getContractEndDate());
        }

        //更新客户表客户状态
        if (ContractTypeEnum.MEMBERSHIP_NEW_CONTRACT.getContractTypeCode().equals(customerContract.getContractType())) {
            //新单合同(新单/续费客户---0:新单客户;1: 续费客户)
            Customer customer = new Customer();
            customer.setCustomerId(oldContract.getCustomerId());
            customer.setNewOrderRenewalCustomer(0);
            customerDbService.updateCustomerById(customer);

        } else if (ContractTypeEnum.MEMBERSHIP_RENEWAL_CONTRACT.getContractTypeCode().equals(customerContract.getContractType())) {
            //续费合同
            if(ContractTypeEnum.MEMBER_SINGLE_CONTRACT.getContractTypeCode().equals(oldContract.getContractType())){
                //会员单次合同 补款升级成续费合同更新会员主合同id
                customerContract.setMasterMembershipContract(updateContractAddQO.getMasterMembershipContract());
                //判断续费类型
                if ((new Date()).getTime() < updateContractAddQO.getContractEndDate().getTime()) {
                    //合同提前续费
                    customerContract.setContractRenewal("2");
                }else {
                    //合同延期续费
                    customerContract.setContractRenewal("3");
                }
            }else{
                //补款升级成续费合同更新会员主合同id
                customerContract.setMasterMembershipContract(oldContract.getMasterMembershipContract());
                //因为补款升级合同利用之前的合同的创建时间和完成时间，所以合同续费类型也采用之前合同的续费类型
                customerContract.setContractRenewal(oldContract.getContractRenewal());
            }

            //新单合同(新单/续费客户---0:新单客户;1: 续费客户)
            Customer customer = new Customer();
            customer.setCustomerId(oldContract.getCustomerId());
            customer.setNewOrderRenewalCustomer(1);
            customerDbService.updateCustomerById(customer);
        }

        customerContract.setAffiliationCompanyId(userAccount.getCompanyId());
        //合同支付方式
        customerContract.setPaymentMethod(updateContractAddQO.getPaymentMethod());
        customerContract.setContactId(oldContract.getContactId());
        customerContract.setContactName(oldContract.getContactName());
        customerContract.setContactDetails(oldContract.getContactDetails());
        customerContract.setReviewAnnexId(updateContractAddQO.getReviewAnnexAccessUrl());
//        customerContract.setContractTotalAmount(customerContractAddQO.getContractTotalAmount());
//        customerContract.setContractDiscountTotalAmount(customerContractAddQO.getContractDiscountTotalAmount());
        customerContract.setApplyElectronicContract(updateContractAddQO.getApplyElectronicContract());
        //商机
        customerContract.setOpportunityId(updateContractAddQO.getOpportunityId());
        //跟进记录
        customerContract.setFollowRecordId(updateContractAddQO.getFollowRecordId());
        customerContract.setContractReceivables(updateContractAddQO.getReplenishmentAmount());
        customerContract.setContractReviewNotes(updateContractAddQO.getContractReviewNotes());
        customerContract.setWhetherKeepSecret(oldContract.getWhetherKeepSecret());
        customerContract.setUpgradeRelateFinishProductId(updateContractAddQO.getFinishOrderProductId());

        //没有优惠价，先把特批设置为不是特批
        customerContract.setSpecialApprovalStatus("0");

        customerContract.setUpdatePeopleId(userAccount.getAccountId());
        customerContract.setUpdateTm(new Date());
        //新建合同
        contractId = CommonUtils.getGUID();
        customerContract.setContractId(contractId);
        Random rand = new Random();
        int k = rand.nextInt(999);
        String contractNumber = "C" + new Date().getTime()+k;
        customerContract.setContractNumber(contractNumber);
        //合同状态:1-未生效；2-生效中；3-已结束；4-已作废；5-意外终止；6-挂起
        customerContract.setContractStatus("1");
        //删除状态
        customerContract.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        //锁定状态
        customerContract.setLockedState("0");
        //回款状态
        customerContract.setPaymentStatus("0");
        //审批状态
        customerContract.setContractApprovalStatus("0");
        //审核状态
        customerContract.setContractReviewStatus("0");
        //提成发放状态--1:已全部发放；2:部分发放;3:未发放
        customerContract.setCommissionStatus("3");
        //是否挂起
        customerContract.setWhetherHang("0");
        //创建人
        customerContract.setCreatePeopleId(userAccount.getAccountId());
        //创建时间
        customerContract.setCreateTm(new Date());

        //判断合同分类是否为空
        if (updateContractAddQO.getContractCategory()!=null) {
            customerContract.setContractCategory(updateContractAddQO.getContractCategory());
        }

        //新增合同
        Boolean result = customerContractDbService.insertCustomerContract(customerContract);
        if(result&&!StringUtils.isBlank(updateContractAddQO.getOpportunityId())){
            //修改商机表中商机合同
            Opportunity opportunity = new Opportunity();
            opportunity.setOpportunityId(updateContractAddQO.getOpportunityId());
            opportunity.setOpportunityContractType("1");
            opportunity.setUpdateTm(new Date());
            opportunity.setUpdatePeopleId(userAccount.getAccountId());
            opportunityDbService.updateOpportunityId(opportunity);
        }
        ESUtil.syncConctract(contractId,ESurl);
        return customerContract;
    }

    /**
     * 添加订单
     *
     * @param customerContract 合同信息
     * @return
     * @author luojie
     */
    public CustomerProductOrder addContractOrder(CustomerContract customerContract) {
        JSONObject result = new JSONObject();
        String orderId = CommonUtils.getGUID();
        CustomerProductOrder customerProductOrder = new CustomerProductOrder();
        customerProductOrder.setProductOrderId(orderId);
        //订单类型(根据合同里面的会员类型来判断)--0:非会员订单;1:会员订单
        customerProductOrder.setOrderType(customerContract.getWhetherCheck());
        customerProductOrder.setOrderPaymentWay(customerContract.getPaymentMethod());
        customerProductOrder.setOrderActualTotalAmount(customerContract.getContractActualTotalAmount());
/*        customerProductOrder.setOrderDiscountTotalAmount(customerContractAddQO.getContractDiscountTotalAmount());
        customerProductOrder.setOrderTotalAmount(customerContractAddQO.getContractTotalAmount());
        customerProductOrder.setOrderSurcharge(customerContractAddQO.getOrderSurcharge());
        customerProductOrder.setOrderSurchargeRemark(customerContractAddQO.getOrderSurchargeRemark());*/
        customerProductOrder.setContactPerson(customerContract.getContactName());
        customerProductOrder.setBindMobilePhoneNumber(customerContract.getContactDetails());
        customerProductOrder.setCustomerEmail(customerContract.getCustomerEmail());
        customerProductOrder.setContractType(customerContract.getContractType());
        //是否合作开发
        customerProductOrder.setWhetherCoDevelopment(customerContract.getWhetherCooperateDevelopment());

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        customerProductOrder.setUpdatePeopleId(userAccount.getAccountId());
        customerProductOrder.setUpdateTm(new Date());
        customerProductOrder.setAffiliationCompanyId(userAccount.getCompanyId());
        customerProductOrder.setCustomerId(customerContract.getCustomerId());
        customerProductOrder.setCustomerName(customerContract.getCustomerName());
        customerProductOrder.setContractOtherType("1");
        //不是老订单
        customerProductOrder.setOldOrder("0");

        //订单编码
        Random rand = new Random();
        int k = rand.nextInt(999);
        String orderNumber = "D" + String.valueOf(new Date().getTime())+k;
        customerProductOrder.setOrderNumber(orderNumber);
        //是否挂起--1:是;2-否
        customerProductOrder.setWhetherSuspend("2");
        //订单状态--1:等待回款;2:已完成;3:作废
        customerProductOrder.setOrderStatus("1");
        customerProductOrder.setCreatePeopleId(userAccount.getAccountId());
        customerProductOrder.setCreateTm(new Date());
        customerProductOrder.setContractId(customerContract.getContractId());
        customerProductOrder.setContractNumber(customerContract.getContractNumber());
        //新增订单
        Boolean insertResult = customerProductOrderDbService.insertProductOrder(customerProductOrder);
        return customerProductOrder;
    }

    /**
     * 新增合同开发人员
     *
     * @param updateContractAddQO 新增对象
     * @param contractId    新增合同id
     * @param orderId       新增订单id
     * @author luojie
     */
    public void addContractDeveloper(UpdateContractAddQO updateContractAddQO,String contractId,String orderId) {
        //合同实际总金额
        BigDecimal contractReceivables = updateContractAddQO.getReplenishmentAmount();

        List<ContractCoDeveloperQO> coDeveloperList = updateContractAddQO.getCoDeveloperList();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if(coDeveloperList!=null && coDeveloperList.size()>0){
            for (ContractCoDeveloperQO contractCoDeveloperQO : coDeveloperList) {
                //如果合作开发人员的用户id为空则不进行保存
                if(StringUtils.isBlank(contractCoDeveloperQO.getUserId())){
                    continue;
                }

                CustomerContractDeveloper customerContractDeveloper = new CustomerContractDeveloper();
                UserAccount userAccount1 = userAccountService.selectUserAccountByAccountId(contractCoDeveloperQO.getUserId());

                if(userAccount1==null){
                    continue;
                }
                customerContractDeveloper.setCoDeveloper(userAccount1.getUserId());
                customerContractDeveloper.setContractDeveloperId(CommonUtils.getGUID());
                customerContractDeveloper.setContractId(contractId);
                customerContractDeveloper.setOrderId(orderId);

                customerContractDeveloper.setUserName(contractCoDeveloperQO.getUserName());
                customerContractDeveloper.setCompanyId(contractCoDeveloperQO.getCompanyId());
                customerContractDeveloper.setCreateTm(new Date());
                customerContractDeveloper.setCreatePeopleId(userAccount.getAccountId());
                customerContractDeveloper.setAllocationMount(contractCoDeveloperQO.getAllocationMount());
                customerContractDeveloper.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
                //计算合同合作开发分配比例
                BigDecimal allocationRatio = contractCoDeveloperQO.getAllocationMount().divide(updateContractAddQO.getReplenishmentAmount(),5,BigDecimal.ROUND_DOWN);
                customerContractDeveloper.setAllocationRatio(allocationRatio);
                customerContractDeveloperDbService.insertCustomerContractDeveloper(customerContractDeveloper);
                if(contractCoDeveloperQO.getAllocationMount()!=null){
                    contractReceivables = contractReceivables.subtract(contractCoDeveloperQO.getAllocationMount());
                }

            }

            //如果给自己最后分配的份额不为0，则最后再保存创建人自己
            if(contractReceivables!=BigDecimal.ZERO){
                CustomerContractDeveloper customerContractDeveloper = new CustomerContractDeveloper();
                customerContractDeveloper.setContractDeveloperId(CommonUtils.getGUID());
                customerContractDeveloper.setContractId(contractId);
                customerContractDeveloper.setOrderId(orderId);
                customerContractDeveloper.setCoDeveloper(userAccount.getUserId());
                customerContractDeveloper.setUserName(userAccount.getUserName());
                customerContractDeveloper.setCompanyId(userAccount.getCompanyId());
                customerContractDeveloper.setCreateTm(new Date());
                customerContractDeveloper.setCreatePeopleId(userAccount.getAccountId());
                customerContractDeveloper.setAllocationMount(contractReceivables);
                customerContractDeveloper.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
                //计算合同合作开发分配比例
                BigDecimal allocationRatio = contractReceivables.divide(updateContractAddQO.getReplenishmentAmount(),5,BigDecimal.ROUND_DOWN);
                customerContractDeveloper.setAllocationRatio(allocationRatio);
                customerContractDeveloperDbService.insertCustomerContractDeveloper(customerContractDeveloper);
            }
        }
    }

    /**
     * 新增订单明细
     *
     * @param updateContractAddQO
     * @param orderId               订单Id
     * @return
     * @author luojie
     */
    public Boolean addOrderDetail(UpdateContractAddQO updateContractAddQO, String orderId) {
        //查询补款升级的产品
        CustomerMemberProduct customerMemberProduct = customerMemberProductDbService.selectMemberProductById(updateContractAddQO.getUpdateProductId());
        CustomerProductOrderDetail customerProductOrderDetail = new CustomerProductOrderDetail();
        customerProductOrderDetail.setProductOrderDetailId(CommonUtils.getGUID());
        customerProductOrderDetail.setOrderDetailName(updateContractAddQO.getUpdateProductName());
        customerProductOrderDetail.setProductCode(customerMemberProduct.getMemberProductCode());
        customerProductOrderDetail.setProductCategories("1");
/*            customerProductOrderDetail.setProductOriginalPrice(customerMemberProduct.getProductOriginalPrice());
        customerProductOrderDetail.setProductUnitPrice(customerMemberProduct.getProductUnitPrice());*/
        customerProductOrderDetail.setProductMemberPrice(customerMemberProduct.getSellingCardPrice());
        customerProductOrderDetail.setProductFinalPrice(updateContractAddQO.getReplenishmentAmount());
        customerProductOrderDetail.setProductQuantity(1);
        customerProductOrderDetail.setProductOrderDetailType("1");
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        customerProductOrderDetail.setCreatePeopleId(userAccount.getAccountId());
        customerProductOrderDetail.setCreateTm(new Date());
        customerProductOrderDetail.setUpdatePeopleId(userAccount.getAccountId());
        customerProductOrderDetail.setUpdateTm(new Date());
        customerProductOrderDetail.setOrderRelationId(updateContractAddQO.getUpdateProductId());
        customerProductOrderDetail.setProductOrderId(orderId);
        customerProductOrderDetail.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
        customerProductOrderDetailDbService.insertCustomerProductOrderDetail(customerProductOrderDetail);
        return true;
    }

    /***
     * @Description:插入finish表
     * @Param: orderId 订单id
     * @Author: luojie
     * @Date: 2021/9/7 18:46
     */
    public void insertFinishOrderProduct(CustomerContract customerContract,String orderId,String orderNumber){
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        FinishOrderProduct finishOrderProduct = new FinishOrderProduct();
        finishOrderProduct.setContractType(customerContract.getContractType());
        finishOrderProduct.setProductOrderId(orderId);
        finishOrderProduct.setOrderNumber(orderNumber);
        finishOrderProduct.setContractNumber(customerContract.getContractNumber());
        finishOrderProduct.setCooperateType(customerContract.getWhetherCooperateDevelopment());
        finishOrderProduct.setSalesmanId(userAccount.getAccountId());
        finishOrderProduct.setCompanyId(userAccount.getCompanyId());
        finishOrderProduct.setCustomerName(customerContract.getCustomerName());
        finishOrderProduct.setCreatePeopleId(userAccount.getAccountId());
        finishOrderProduct.setCreateTm(new Date());
        finishOrderProduct.setUpdatePeopleId(userAccount.getAccountId());
        finishOrderProduct.setUpdateTm(new Date());

        //1、插入产品
        List<CustomerProductOrderDetail> productOrderDetailList = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(orderId, "1");
        if(productOrderDetailList.size()>0){
            CustomerProductOrderDetail customerProductOrderDetail = productOrderDetailList.get(0);
            finishOrderProduct.setFinishOrderProductId(CommonUtils.getGUID());
            finishOrderProduct.setProductId(customerProductOrderDetail.getOrderRelationId());
            finishOrderProduct.setProductName(customerProductOrderDetail.getOrderDetailName());
            finishOrderProduct.setProductOriginalPrice(customerProductOrderDetail.getProductOriginalPrice());
            finishOrderProduct.setProductUnitPrice(customerProductOrderDetail.getProductUnitPrice());
            finishOrderProduct.setProductFinalPrice(customerProductOrderDetail.getProductFinalPrice());
            finishOrderProduct.setProductMemberPrice(customerProductOrderDetail.getProductMemberPrice());
            //优惠价不存
            finishOrderProduct.setProductCode(customerProductOrderDetail.getProductCode());
            finishOrderProduct.setProductQuantity(customerProductOrderDetail.getProductQuantity());
            finishOrderProduct.setOrderDetailType("1");
            finishOrderProduct.setProductCategories(customerProductOrderDetail.getProductCategories());
            finishOrderProduct.setProductOrderDetailId(customerProductOrderDetail.getProductOrderDetailId());
            finishOrderProduct.setOrderRelationId(customerProductOrderDetail.getOrderRelationId());

            //如果是合作开发，产品号前面加个H
            if ("1".equals(customerContract.getWhetherCooperateDevelopment())){
                finishOrderProduct.setFinishOrderProductNum("H" + new Date().getTime());
            }else{
                finishOrderProduct.setFinishOrderProductNum(String.valueOf(new Date().getTime()));
            }
            //业绩换算比例
            BigDecimal ratio = customerMemberProductDbService.selectProductPerformanceRatio(finishOrderProduct.getProductCategories(),finishOrderProduct.getProductId());
            finishOrderProduct.setPerformanceConversionRatio(ratio);
            int insertProduct = finishOrderDBservice.insertFinishProduct(finishOrderProduct);
        }

    }

    /***
     * @Description:根据订单id作废会员卡
     * @Param: orderId 订单id
     * @Author: luojie
     * @Date: 2021/9/24 10:07
     */
    public void invalidMembershipCard(String orderId){
        List<FinishOrderProduct> finishOrderProductList = finishOrderDBservice.selectFinishOrderProductList("1","1",orderId);
        finishOrderProductList.stream().forEach(finishOrderProduct -> {
            customerProductOrderService.backProduct(orderId,finishOrderProduct.getFinishOrderProductNum());
        });
    }
}
